/** Copyright 2014, Ross Mahony. Some rights reserved. See COPYING. */
package models

import play.api.db.slick.Config.driver.simple._
import scala.slick.lifted.Tag

case class Scheme(id: Option[Long], name: String, description: String, url: String)
case class SchemeMeasure(schemeMeasureId: Long, measureId: Long)

/** Scheme entity. */
class SchemeTbl(tag: Tag) extends Table[Scheme](tag, "SCHM") {
  def id = column[Long]("ID", O.PrimaryKey, O.AutoInc)
  def name = column[String]("NAME", O.NotNull)
  def description = column[String]("DESCR", O.Nullable)
  def url = column[String]("URL", O.Nullable)
  def * = (id.?, name, description, url) <> (Scheme.tupled, Scheme.unapply _)
}

/** Scheme entity. */
class SchemeMeasureTbl(tag: Tag) extends Table[SchemeMeasure](tag, "SCHM_MSR") {

  def schemeMeasureId = column[Long]("SCHM_ID", O.NotNull)
  def measureId = column[Long]("MSR_ID", O.NotNull)
  def * = (schemeMeasureId, measureId) <> (SchemeMeasure.tupled, SchemeMeasure.unapply _)
}

/** Scheme DAO */
object SchemeDAO {
  val schemes = TableQuery[SchemeTbl]
  val schemeMeasures = TableQuery[SchemeMeasureTbl]
  
 /**
  * Retrieve a [[models.Scheme]] by the id
  *
  * @param id
  */
  def findById(id: Long)(implicit s: Session): Option[Scheme] =
  schemes.where(_.id === id).firstOption


 /** Count all schemes */
  def count(implicit s: Session): Int =
  Query(schemes.length).first

 /**
  * Insert a new [[models.Scheme]]
  *
  * @param scheme
  */
  def insert(scheme: Scheme)(implicit s: Session) {
    schemes.insert(scheme)
  }

 /**
  * Insert a new [[models.Scheme]] by ignoring auto inc column
  *
  * @param scheme
  */
  def forceInsert(scheme: Scheme)(implicit s: Session) {
    schemes.forceInsert(scheme)
  }

 /** Delete all schemes */
  def deleteAll(implicit s: Session) {
    schemes.delete
  }


}
